package tools

import (
	"github.com/bwmarrin/snowflake"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"
)

//驼峰转下划线
func SnakeString(s string) string {
	data := make([]byte, 0, len(s)*2)
	j := false
	num := len(s)
	for i := 0; i < num; i++ {
		d := s[i]
		if i > 0 && d >= 'A' && d <= 'Z' && j {
			data = append(data, '_')
		}
		if d != '_' {
			j = true
		}
		data = append(data, d)
	}
	return strings.ToLower(string(data[:]))
}

//下划线转驼峰
func CamelString(s string) string {
	data := make([]byte, 0, len(s))
	j := false
	k := false
	num := len(s) - 1
	for i := 0; i <= num; i++ {
		d := s[i]
		if k == false && d >= 'A' && d <= 'Z' {
			k = true
		}
		if d >= 'a' && d <= 'z' && (j || k == false) {
			d = d - 32
			j = false
			k = true
		}
		if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
			j = true
			continue
		}
		data = append(data, d)
	}
	return string(data[:])
}

// LowerFirst lower first char
func LowerFirst(s string) string {
	if len(s) == 0 {
		return s
	}
	rs := []rune(s)
	f := rs[0]
	if 'A' <= f && f <= 'Z' {
		return string(unicode.ToLower(f)) + string(rs[1:])
	}
	return s
}

// UpperFirst upper first char
func UpperFirst(s string) string {
	if len(s) == 0 {
		return s
	}
	rs := []rune(s)
	f := rs[0]
	if 'a' <= f && f <= 'z' {
		return string(unicode.ToUpper(f)) + string(rs[1:])
	}
	return s
}

// Utf8Len of the string
func Utf8Len(s string) int {
	return utf8.RuneCount([]byte(s))
}

//判断字符串是否为中文[精确度需要反复试验]
func IsContainCN(str string) bool {
	var hzRegexp = regexp.MustCompile("[\u4e00-\u9fa5]+")
	return hzRegexp.MatchString(str)
}


//生成新ID
var snowFlakeNode *snowflake.Node

func NewSnowflakeId() (int64, error) {
	if snowFlakeNode == nil {
		node, err := snowflake.NewNode(1)
		if err != nil {
			return 0, err
		}
		snowFlakeNode = node
	}
	// Generate a snowflake ID.
	id := snowFlakeNode.Generate()
	return id.Int64(), nil
}